<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>MongoDB教程 | 乘风破浪</title><meta name="keywords" content="MongoDB"><meta name="author" content="PAN"><meta name="copyright" content="PAN"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="一、基本命令启动数据库 1mongod  进入 mongo 命令环境 1mongo  显示所有数据库 1show dbs  使用某个数据库，如果当前不存在这个数据库的话会自动新建 1use 数据库名称  显示数据库内的集合 1show collections  当前在哪个库中 1db  CRUD操作 可查看官网文档 新建数据集合和插入数据，比如当前在 test01 数据库中。插入数据会自动生成 1">
<meta property="og:type" content="article">
<meta property="og:title" content="MongoDB教程">
<meta property="og:url" content="https://geekweb.site/2019/02/26/MongoDB%E6%95%99%E7%A8%8B/index.html">
<meta property="og:site_name" content="乘风破浪">
<meta property="og:description" content="一、基本命令启动数据库 1mongod  进入 mongo 命令环境 1mongo  显示所有数据库 1show dbs  使用某个数据库，如果当前不存在这个数据库的话会自动新建 1use 数据库名称  显示数据库内的集合 1show collections  当前在哪个库中 1db  CRUD操作 可查看官网文档 新建数据集合和插入数据，比如当前在 test01 数据库中。插入数据会自动生成 1">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2021/03/26/MqUoIzW5PfNgQKE.png">
<meta property="article:published_time" content="2019-02-25T16:15:33.000Z">
<meta property="article:modified_time" content="2021-03-26T03:31:51.597Z">
<meta property="article:author" content="PAN">
<meta property="article:tag" content="MongoDB">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2021/03/26/MqUoIzW5PfNgQKE.png"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://geekweb.site/2019/02/26/MongoDB%E6%95%99%E7%A8%8B/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":false,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-03-26 11:31:51'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    })(window)</script><meta name="generator" content="Hexo 5.2.0"><link rel="alternate" href="/atom.xml" title="乘风破浪" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://i.loli.net/2020/09/25/RVKnjUAof6kryGi.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">13</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">25</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">7</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://i.loli.net/2021/03/26/MqUoIzW5PfNgQKE.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">乘风破浪</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">MongoDB教程</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2019-02-25T16:15:33.000Z" title="发表于 2019-02-26 00:15:33">2019-02-26</time><span class="post-meta-separator"></span></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E7%BC%96%E7%A8%8B/">编程</a></span></div><div class="meta-secondline"></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="一、基本命令"><a href="#一、基本命令" class="headerlink" title="一、基本命令"></a>一、基本命令</h2><p>启动数据库</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mongod</span><br></pre></td></tr></table></figure>

<p>进入 mongo 命令环境</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mongo</span><br></pre></td></tr></table></figure>

<p>显示所有数据库</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">show dbs</span><br></pre></td></tr></table></figure>

<p>使用某个数据库，如果当前不存在这个数据库的话会自动新建</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">use 数据库名称</span><br></pre></td></tr></table></figure>

<p>显示数据库内的集合</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">show collections</span><br></pre></td></tr></table></figure>

<p>当前在哪个库中</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db</span><br></pre></td></tr></table></figure>

<p>CRUD操作 可查看<a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/crud/">官网文档</a></p>
<h3 id="新建"><a href="#新建" class="headerlink" title="新建"></a>新建</h3><p>数据集合和插入数据，比如当前在 test01 数据库中。<br>插入数据会自动生成</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">use test01     &#x2F;&#x2F; 如果当前没有 test01 数据库则会自动新建  </span><br><span class="line">show dbs       &#x2F;&#x2F; 如果 test01 是空白的，使用这个命令 test01 不会显示在结果列表中，必须不是空的才能显示  </span><br><span class="line">db.user.insert(&#123;&quot;name&quot;:&quot;PAN&quot;, &quot;age&quot;:&quot;18&quot;, &quot;job&quot;:&quot;web engineer&quot;&#125;)   &#x2F;&#x2F; 在 test01 中插入一个名为 user 的集合  </span><br><span class="line">db.user.insert(&#123;&quot;name&quot;:&quot;TING&quot;, &quot;age&quot;:&quot;16&quot;, &quot;job&quot;:&quot;seo manerge&quot;&#125;)   &#x2F;&#x2F; 再插入一条数据  </span><br></pre></td></tr></table></figure>

<h3 id="查找"><a href="#查找" class="headerlink" title="查找"></a>查找</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">db.user.find()    &#x2F;&#x2F; 查找 user 中的所有数据，这样就可以查看刚刚上面添加的那两条数据了</span><br><span class="line">db.user.find().count()  &#x2F;&#x2F; 长度</span><br><span class="line">db.user.findOne() &#x2F;&#x2F; 查找集合中符合条件的第一条数据</span><br><span class="line">&#x2F;&#x2F; db.user.findOnd(&#123;age:18&#125;).name</span><br></pre></td></tr></table></figure>

<h3 id="修改"><a href="#修改" class="headerlink" title="修改"></a>修改</h3><p>db.集合.updata({条件查询}, {修改})</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.user.update(&#123;&quot;name&quot;:&quot;YU&quot;&#125;,&#123;&quot;name&quot;:&quot;YONGYU&quot;, &quot;age&quot;:&quot;19&quot;&#125;)  &#x2F;&#x2F; 需要注意修改的新对象会直接覆盖原来的旧的对象。如果是需要修改指定的属性而不是替换旧对象，参考下面关于updata修改器的教程</span><br></pre></td></tr></table></figure>

<h3 id="删除数据"><a href="#删除数据" class="headerlink" title="删除数据"></a>删除数据</h3><p>db.集合.remove({条件})</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.user.remove(&#123;&quot;name&quot;:&quot;001&quot;&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="删除集合"><a href="#删除集合" class="headerlink" title="删除集合"></a>删除集合</h3><p>db.collection.drop()</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.test01.drop()  &#x2F;&#x2F; 返回 true 表示成功</span><br></pre></td></tr></table></figure>

<h3 id="删除数据库"><a href="#删除数据库" class="headerlink" title="删除数据库"></a>删除数据库</h3><p>db.dropDatabase()</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.dropDatabase()</span><br></pre></td></tr></table></figure>

<h2 id="二、用JS写mongo语句"><a href="#二、用JS写mongo语句" class="headerlink" title="二、用JS写mongo语句"></a>二、用JS写mongo语句</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">var userName &#x3D; &quot;TINGER&quot;; &#x2F;&#x2F; 定义用户名</span><br><span class="line">var timeStamp &#x3D; Date.parse(new Date()); &#x2F;&#x2F; 定义时间戳</span><br><span class="line">var jsonDatabase &#x3D; &#123;&quot;username&quot;: userName, &quot;loginTime&quot;: timeStamp&#125; &#x2F;&#x2F; 要插入的数据</span><br><span class="line">var db &#x3D; connect(&#39;test01&#39;);  &#x2F;&#x2F; 链接 test01 数据库</span><br><span class="line">db.user.insert(jsonDatabase); &#x2F;&#x2F; user 集合插入数据</span><br><span class="line"></span><br><span class="line">print(&#39;[log]:: print success!&#39;);</span><br></pre></td></tr></table></figure>

<h2 id="三、批量插入"><a href="#三、批量插入" class="headerlink" title="三、批量插入"></a>三、批量插入</h2><p>如果是3.2以前版本则需要使用 batchInsert()</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">show dbs</span><br><span class="line">use test02</span><br><span class="line">db.test02.insert([&#123;&quot;_id&quot;:1&#125;,&#123;&quot;_id&quot;:2&#125;,&#123;&quot;_id&quot;:3&#125;])</span><br><span class="line">db.test02.find()    &#x2F;&#x2F; 查看插入结果</span><br></pre></td></tr></table></figure>

<p>插入性能测试</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">var startTime &#x3D; (new Date()).getTime();</span><br><span class="line">var db &#x3D; connect(&#39;test02&#39;); &#x2F;&#x2F; 链接数据库</span><br><span class="line">var tempArr &#x3D; [];</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 循环插入（不建议）</span><br><span class="line">&#x2F;&#x2F; for(let i&#x3D;0; i&lt;1000; i++)&#123;</span><br><span class="line">&#x2F;&#x2F;   db.user.insert(&#123;num:1&#125;)</span><br><span class="line">&#x2F;&#x2F; &#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 性能优化</span><br><span class="line">for(let i&#x3D;0; i&lt;1000; i++)&#123;</span><br><span class="line">  tempArr.push(&#123;num:1&#125;)</span><br><span class="line">&#125;</span><br><span class="line">db.user.insert(tempArr);</span><br><span class="line"></span><br><span class="line">var runTime &#x3D; (new Date()).getTime() - startTime;</span><br><span class="line"></span><br><span class="line">print(&#39;[log]:: runtime is &#39;+runTime+&#39;ms&#39;);</span><br></pre></td></tr></table></figure>

<h2 id="四、update-修改器"><a href="#四、update-修改器" class="headerlink" title="四、update 修改器"></a>四、update 修改器</h2><p>$set 修改</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">db.company.update(&#123;&quot;name&quot;:&quot;TING&quot;&#125;,&#123;&quot;$set&quot;:&#123;&quot;age&quot;:20&#125;&#125;) &#x2F;&#x2F; 修改 age</span><br><span class="line">db.company.update(&#123;&quot;name&quot;:&quot;TING&quot;&#125;,&#123;&quot;$set&quot;:&#123;&quot;skill.s1&quot;:&quot;Excel&quot;&#125;&#125;)  &#x2F;&#x2F; 修改嵌套的s1。 skill.s1</span><br></pre></td></tr></table></figure>

<p>$unset 删除</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">db.company.update(&#123;&quot;name&quot;:&quot;TING&quot;&#125;,&#123;&quot;$unset&quot;:&#123;&quot;age&quot;:&#39;&#39;&#125;&#125;)  &#x2F;&#x2F; 删除age年龄。age 的值随便写，$unset 时只关心 key</span><br><span class="line">db.company.update(&#123;&quot;name&quot;:&quot;TING&quot;&#125;,&#123;&quot;$set&quot;:&#123;&quot;age&quot;:20&#125;&#125;)  &#x2F;&#x2F; 重新添加 age。$set 当修改的属性为空时会自己添加</span><br></pre></td></tr></table></figure>

<p>$inc 对数字进行计算</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.company.update(&#123;&quot;name&quot;:&quot;TING&quot;&#125;,&#123;&quot;$inc&quot;:&#123;&quot;age&quot;:-2&#125;&#125;)  &#x2F;&#x2F; age 由原来的值减2</span><br></pre></td></tr></table></figure>

<p>multi选项，有 true 和 false 两个值。默认 false，为 true 时即所有项都添加</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.company.update(&#123;&#125;,&#123;&quot;$set&quot;:&#123;&quot;aihao&quot;:[]&#125;&#125;, &#123;multi:true&#125;)</span><br></pre></td></tr></table></figure>

<p>upsert $set upsert 为 true 添加新项</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.company.update(&#123;&quot;name&quot;:&quot;CUI&quot;&#125;,&#123;&quot;$set&quot;:&#123;&quot;aihao&quot;:[]&#125;&#125;, &#123;upsert:true&#125;)  &#x2F;&#x2F; 如果 CUI 原来不存在，必须 upsert 为 true 才能添加到集合中</span><br></pre></td></tr></table></figure>

<h2 id="五、update数组修改器"><a href="#五、update数组修改器" class="headerlink" title="五、update数组修改器"></a>五、update数组修改器</h2><p>$push 追加</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.company.update(&#123;&quot;name&quot;:&quot;TING&quot;&#125;,&#123;$push:&#123;&quot;aihao&quot;:&quot;shoping&quot;&#125;&#125;)  &#x2F;&#x2F; 在 aihao 项数组中添加 shoping</span><br></pre></td></tr></table></figure>

<p>$ne 查找是否存在。没有则修改，有则不修改。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.company.update(&#123;&quot;name&quot;:&quot;PAN&quot;, &quot;aihao&quot;:&#123;$ne:&quot;palygame&quot;&#125;&#125;, &#123;$push:&#123;&quot;aihao&quot;:&quot;Game&quot;&#125;&#125;) &#x2F;&#x2F; ...</span><br></pre></td></tr></table></figure>

<p>$addToSet 查找是否存在，不存在就 push，$ne 的升级版，工作用使用更多</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.company.update(&#123;&quot;name&quot;:&quot;TING&quot;&#125;, &#123;$addToSet:&#123;&quot;aihao&quot;:&quot;跳舞&quot;&#125;&#125;)</span><br></pre></td></tr></table></figure>

<p>$each 批量追加</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var arr &#x3D; [&#39;唱歌&#39;, &#39;跳舞&#39;, &#39;读书&#39;];</span><br><span class="line">db.company.update(&#123;&quot;name&quot;:&quot;TING&quot;&#125;, &#123;$addToSet:&#123;&quot;aihao&quot;:&#123;$each:arr&#125;&#125;&#125;)</span><br></pre></td></tr></table></figure>

<p>$pop 删除。1 删除末位，-1删除首位</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.company.update(&#123;&quot;name&quot;:&quot;TING&quot;&#125;, &#123;$pop:&#123;&quot;aihao&quot;:1&#125;&#125;)</span><br></pre></td></tr></table></figure>

<p>数组定位修改</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.company.update(&#123;&quot;name&quot;:&quot;TING&quot;&#125;, &#123;$set:&#123;&quot;aihao.1&quot;:&quot;画画&quot;&#125;&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="六、修改的状态返回与安全"><a href="#六、修改的状态返回与安全" class="headerlink" title="六、修改的状态返回与安全"></a>六、修改的状态返回与安全</h2><p>runCommand 是数据库运行命令的执行器，执行命令首选就要使用它，因为它在Shell和驱动程序间提供了一致的接口。（几乎操作数据库的所有操作，都可以使用runCommand来执行）</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">db.runCommand():</span><br><span class="line">&#x2F;&#x2F; 例如</span><br><span class="line">db.runCommand(&#123;getLastError:1&#125;&#125;):  &#x2F;&#x2F;getLastError:1 :表示返回功能错误，这里的参数很多，如果有兴趣请自行查找学习，这里不作过多介绍</span><br><span class="line">db.runCommand(&#123;ping:1&#125;&#125;):  &#x2F;&#x2F; 查看数据库链接是否成功</span><br></pre></td></tr></table></figure>

<p>findAndModify<br>findAndModify 属性值  </p>
<ol>
<li>query: 要查询的条件/文档</li>
<li>sort: 进行排序</li>
<li>remove：[boolean]是否删除查找到的文档，值填写true，可以删除。</li>
<li>new:[boolean]返回更新前的文档还是更新后的文档。</li>
<li>fields：需要返回的字段</li>
<li>upsert：没有这个值是否增加。</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">var myModify &#x3D; &#123;</span><br><span class="line">  findAndModify: &quot;user&quot;,</span><br><span class="line">  query: &#123;name: &quot;PAN&quot;&#125;,</span><br><span class="line">  update: &#123;$set:&#123;age:20&#125;&#125;,</span><br><span class="line">  new: true</span><br><span class="line">&#125;</span><br><span class="line">var resultMsg &#x3D; db.runCommand(myModify)</span><br><span class="line">printjson(resultMsg)  &#x2F;&#x2F; 表示以json对象的格式输出到控制台</span><br></pre></td></tr></table></figure>

<p>返回状态结果</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    &quot;lastErrorObject&quot; : &#123;</span><br><span class="line">        &quot;updatedExisting&quot; : true, &#x2F;&#x2F; 成功</span><br><span class="line">        &quot;n&quot; : 1</span><br><span class="line">    &#125;,</span><br><span class="line">    &quot;value&quot; : &#123;  &#x2F;&#x2F; 返回修改后的结果</span><br><span class="line">        &quot;_id&quot; : ObjectId(&quot;5c6d1bac1c8ca3a357fdf9a7&quot;),</span><br><span class="line">        &quot;name&quot; : &quot;PAN&quot;,</span><br><span class="line">        &quot;age&quot; : 20</span><br><span class="line">    &#125;,</span><br><span class="line">    &quot;ok&quot; : 1</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="七、查询：find的不等修饰符"><a href="#七、查询：find的不等修饰符" class="headerlink" title="七、查询：find的不等修饰符"></a>七、查询：find的不等修饰符</h2><p>简单查找</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.company.find(&#123;&quot;skill.skillOne&quot;:&quot;HTML+CSS&quot;&#125;)</span><br></pre></td></tr></table></figure>

<p>筛选字段<br>第二个参数控制显示哪些字段。示例：显示 name 和 skill.skillOne 字段，隐藏 _id 字段</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.company.find(&#123;&quot;skill.skillOne&quot;:&quot;HTML+CSS&quot;&#125;,&#123;name:true,&quot;skill.skillOne&quot;:true,_id:false&#125;)</span><br></pre></td></tr></table></figure>

<p>不等修饰符<br>小于($lt):  英文全称less-than<br>小于等于($lte)：英文全称less-than-equal<br>大于($gt):  英文全称greater-than<br>大于等于($gte):  英文全称greater-than-equal<br>不等于($ne):英文全称not-equal 我们现在要查找一下，公司内年龄小于30大于25岁的人员。看下面的代码。<br>示例：查询年龄大于等于 25，小于等于 30 的人  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.company.find(&#123;&quot;age&quot;:&#123;$gte:25,$lte:30&#125;&#125;,&#123;name:true,&quot;skill.skillOne&quot;:true,_id:false,age:true&#125;)</span><br></pre></td></tr></table></figure>

<p>查找日期<br>示例：查找日期大于2018-01-01的</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var regTime &#x3D; new Date(&quot;01&#x2F;01&#x2F;2018&quot;);</span><br><span class="line">db.company.find(&#123;&quot;regeditTime&quot;:&#123;$gt:regTime&#125;&#125;,&#123;name:true,&quot;skill.skillOne&quot;:true,_id:false,age:true,regeditTime:true&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="八、查询：find的多条件查询"><a href="#八、查询：find的多条件查询" class="headerlink" title="八、查询：find的多条件查询"></a>八、查询：find的多条件查询</h2><p>$in修饰符，一键多值，注意 $in 的值是一个数组<br>示例：查找年龄等于 25 和 33 岁的  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.company.find(&#123;&quot;age&quot;:&#123;$in:[25,33]&#125;&#125;,&#123;name:1,&quot;skill.skillOne&quot;:1,_id:0,age:1&#125;)</span><br></pre></td></tr></table></figure>

<p>$in修饰符，和 $in 相反，就是不包含查询条件的</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.company.find(&#123;&quot;age&quot;:&#123;$nin:[25,33]&#125;&#125;,&#123;name:1,&quot;skill.skillOne&quot;:1,_id:0,age:1&#125;)</span><br></pre></td></tr></table></figure>

<p>$or，或者，类似JS中的或运算 ||<br>示例：查找年龄大于行于30或者技能会PHP的  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">db.company.find(&#123;$or:[</span><br><span class="line">  &#123;age:&#123;$gte:30&#125;&#125;,</span><br><span class="line">  &#123;&quot;skill.skillThree&quot;:&quot;PHP&quot;&#125;</span><br><span class="line">]&#125;,&#123;name:1,&quot;skill.skillThree&quot;:1,_id:0,age:1&#125;)</span><br></pre></td></tr></table></figure>

<p>$and，并且，类似JS中的或运算 &amp;&amp;<br>示例：查找年龄大于行于30并且技能会PHP的  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">db.company.find(&#123;$and:[</span><br><span class="line">  &#123;age:&#123;$gte:30&#125;&#125;,</span><br><span class="line">  &#123;&quot;skill.skillThree&quot;:&quot;PHP&quot;&#125;</span><br><span class="line">]&#125;,&#123;name:1,&quot;skill.skillThree&quot;:1,_id:0,age:1&#125;)</span><br></pre></td></tr></table></figure>

<p>$not修饰符<br>查找除年龄大于20岁，小于30岁的人员信息。需要注意的是$not修饰符不能应用在条件语句中，只能在外边进行查询使用。  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">db.workmate.find(&#123;</span><br><span class="line">    age:&#123;</span><br><span class="line">        $not:&#123;</span><br><span class="line">            $lte:30,</span><br><span class="line">            $gte:20</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;,</span><br><span class="line">&#123;name:1,&quot;skill.skillOne&quot;:1,age:1,_id:0&#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<h2 id="九、查询：find数组查询"><a href="#九、查询：find数组查询" class="headerlink" title="九、查询：find数组查询"></a>九、查询：find数组查询</h2><p>基本数组查询<br>示例：查询兴趣(interest)中有画画的人员  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.workmate.find(&#123;interest:&#39;画画&#39;&#125;,&#123;name:1,interest:1,_id:0&#125;)</span><br><span class="line">&#x2F;&#x2F; 如果画画加了数组的中括则表示要完全匹配条件，例如以下示例则表示要完全匹配有画画和看电影的</span><br><span class="line">db.workmate.find(&#123;interest:[&#39;画画&#39;,&#39;看电影&#39;]&#125;,&#123;name:1,interest:1,_id:0&#125;)</span><br></pre></td></tr></table></figure>

<p>$all 数组多项查询<br>示例：查询兴趣中同时存在画画和看电影两项的  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.workmate.find(&#123;interest:&#123;$all:[&quot;画画&quot;,&quot;看电影&quot;]&#125;&#125;,&#123;name:1,interest:1,_id:0&#125;)</span><br></pre></td></tr></table></figure>

<p>$in 数组的或查询<br>类似JS的或运算，示例：查询兴趣中有画画或者看电影一项的结果  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.workmate.find(&#123;interest:&#123;$in:[&quot;画画&quot;,&quot;看电影&quot;]&#125;&#125;,&#123;name:1,interest:1,_id:0&#125;)</span><br></pre></td></tr></table></figure>

<p>$size 数组个数查询<br>示例：显示兴趣项长度为3的项  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.workmate.find(&#123;interest:&#123;$size:3&#125;&#125;,&#123;name:1,interest:1,_id:0&#125;)</span><br></pre></td></tr></table></figure>

<p>$slice 控制显示长度<br>示例：只显示兴趣数组前两项，也也接受负数，如果-1表示最后一项  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.workmate.find(&#123;interest:&#123;$size:3&#125;&#125;,&#123;name:1,interest:&#123;$slice:2&#125;,_id:0&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="十、查询：find参数"><a href="#十、查询：find参数" class="headerlink" title="十、查询：find参数"></a>十、查询：find参数</h2><p>find查询包含以下几个参数query, fields, limit, skip, batchSize, options，前面的示例用的一直都是query和fields<br>query：这个就是查询条件，MongoDB默认的第一个参数。<br>fields：（返回内容）查询出来后显示的结果样式，可以用true和false控制是否显示。<br>limit：返回的数量，后边跟数字，控制每次查询返回的结果数量。<br>skip:跳过多少个显示，和limit结合可以实现分页。<br>sort：排序方式，从小到大排序使用1，从大到小排序使用-1  </p>
<p>示例：limit显示4条，跳过0条  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">db.workmate.find(&#123;&#125;,&#123;name:1,age:1,_id:0&#125;).limit(4).skip(0)</span><br><span class="line">如果要做分页可以如下编写</span><br><span class="line">db.workmate.find(&#123;&#125;,&#123;name:1,age:1,_id:0&#125;).limit(4).skip(0)  &#x2F;&#x2F; 第一页，每页显示4条，跳过0条数据</span><br><span class="line">db.workmate.find(&#123;&#125;,&#123;name:1,age:1,_id:0&#125;).limit(4).skip(4)  &#x2F;&#x2F; 第二页，每页显示4条，跳过4条数据</span><br><span class="line">db.workmate.find(&#123;&#125;,&#123;name:1,age:1,_id:0&#125;).limit(4).skip(8)  &#x2F;&#x2F; 第三页，每页显示4条，跳过8条数据</span><br></pre></td></tr></table></figure>

<p>示例：对年龄排序，1表示从小到大排序  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.workmate.find(&#123;&#125;,&#123;name:1,age:1,_id:0&#125;).limit(4).skip(0).sort(&#123;age:1&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="十一、索引入门"><a href="#十一、索引入门" class="headerlink" title="十一、索引入门"></a>十一、索引入门</h2><p>普通查询性能测试  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">var startTime &#x3D; (new Date).getTime();</span><br><span class="line"></span><br><span class="line">var db &#x3D; connect(&#39;test02&#39;);</span><br><span class="line">var rs &#x3D; db.randomInfo.find(&#123;username:&#39;dnaugkj&#39;&#125;);</span><br><span class="line">rs.forEach(rs&#x3D;&gt;&#123;printjson(rs)&#125;) </span><br><span class="line"></span><br><span class="line">var runTime &#x3D; (new Date).getTime() - startTime;</span><br><span class="line">print(&#39;[SUCCESS]This run time is:&#39;+runTime+&#39;ms&#39;);</span><br></pre></td></tr></table></figure>

<p>示例结果，大概需要600-800毫秒左右，具体结果和机器有一定关系。  </p>
<p>查看索引  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">db.randomInfo.getIndexes()  &#x2F;&#x2F; randomInfo 为 collections 名称</span><br><span class="line">&#x2F;&#x2F; 查询结果</span><br><span class="line">[</span><br><span class="line">    &#123;</span><br><span class="line">        &quot;v&quot; : 2,</span><br><span class="line">        &quot;key&quot; : &#123;</span><br><span class="line">            &quot;_id&quot; : 1</span><br><span class="line">        &#125;,</span><br><span class="line">        &quot;name&quot; : &quot;_id_&quot;,</span><br><span class="line">        &quot;ns&quot; : &quot;test02.randomInfo&quot;</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">        &quot;v&quot; : 2,</span><br><span class="line">        &quot;key&quot; : &#123;</span><br><span class="line">            &quot;username&quot; : 1</span><br><span class="line">        &#125;,</span><br><span class="line">        &quot;name&quot; : &quot;username_1&quot;,</span><br><span class="line">        &quot;ns&quot; : &quot;test02.randomInfo&quot;</span><br><span class="line">    &#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>建立索引<br>MongoDB 最多只能建立 64 个索引，索引会消耗硬盘和内存资源。  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">db.randomInfo.ensureIndex(&#123;username:1&#125;)</span><br><span class="line">&#x2F;&#x2F; 如果运行正确，建立之后使用 getIndexes 即可查看</span><br></pre></td></tr></table></figure>
<p>建立索引之后再运行一下上面普通查询的代码会发现查询速度会极大提升，约5-10毫秒左右</p>
<p>删除索引  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.randomInfo.dropIndex(&#39;username_1&#39;);  &#x2F;&#x2F; 注意值不是 key 值，而是 name 值</span><br></pre></td></tr></table></figure>

<p>查看运行时间  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.randomInfo.find(&#123;username:&#39;dnaugkj&#39;&#125;).explain(&quot;executionStats&quot;);</span><br></pre></td></tr></table></figure>

<h2 id="十二、复合索引"><a href="#十二、复合索引" class="headerlink" title="十二、复合索引"></a>十二、复合索引</h2><p>数据不超万条时，不需要使用索引。性能的提升并不明显，而大大增加了内存和硬盘的消耗。<br>查询数据超过表数据量30%时，不要使用索引字段查询。实际证明会比不使用索引更慢，因为它大量检索了索引表和我们原表。<br>数字索引，要比字符串索引快的多，在百万级甚至千万级数据量面前，使用数字索引是个明确的选择。<br>把你经常查询的数据做成一个内嵌数据（对象型的数据），然后集体进行索引。  </p>
<p>复合索引就是两个以上的索引  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">var startTime &#x3D; (new Date).getTime();</span><br><span class="line"></span><br><span class="line">var db &#x3D; connect(&#39;test02&#39;);</span><br><span class="line">var rs &#x3D; db.randomInfo.find(&#123;username:&#39;dnaugkj&#39;, randNum0:940739&#125;);</span><br><span class="line">rs.forEach(rs&#x3D;&gt;&#123;printjson(rs)&#125;) </span><br><span class="line"></span><br><span class="line">var runTime &#x3D; (new Date).getTime() - startTime;</span><br><span class="line">print(&#39;[SUCCESS]This run time is:&#39;+runTime+&#39;ms&#39;);</span><br></pre></td></tr></table></figure>

<p>指定索引查询（hint）<br>使用 hint() 方法指定索引优先查询  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">...e</span><br><span class="line">var rs &#x3D; db.randomInfo.find(&#123;username:&#39;dnaugkj&#39;, randNum0:940739&#125;).hint(&#123;randNum0:1&#125;);  &#x2F;&#x2F; randNum0 优先查询</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<h2 id="十四、全文索引"><a href="#十四、全文索引" class="headerlink" title="十四、全文索引"></a>十四、全文索引</h2><p>建立全文索引  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.info.ensureIndex(&#123;&quot;contextInfo&quot;:&quot;text&quot;&#125;)</span><br></pre></td></tr></table></figure>

<p>全文索引查找<br>查找时需要配合两个关键修改符<br>$text:表示要在全文索引中查东西。<br>$search:后边跟查找的内容。  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.info.find(&#123;$text:&#123;$search:&quot;programmer&quot;&#125;&#125;)</span><br></pre></td></tr></table></figure>

<p>多词查询<br>示例：查询包含 drink 或者 life 的记录  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.info.find(&#123;$text:&#123;$search:&quot;drink life&quot;&#125;&#125;)</span><br></pre></td></tr></table></figure>

<p>可以用 - 来排队不需要的记录。示例：排队带有 drink 的记录项  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.info.find(&#123;$text:&#123;$search:&quot;-drink life&quot;&#125;&#125;)</span><br></pre></td></tr></table></figure>

<p>转义符  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">想搜索的是两个词（love PlayGame和drink）</span><br><span class="line">db.info.find(&#123;$text:&#123;$search:&quot;\&quot;love PlayGame\&quot; drink&quot;&#125;&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="十五、管理-用户的创建、删除与修改"><a href="#十五、管理-用户的创建、删除与修改" class="headerlink" title="十五、管理:用户的创建、删除与修改"></a>十五、管理:用户的创建、删除与修改</h2><p>创建用户首先要进入 admin 库，show collections 只有 version 一个集合  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">show dbs</span><br><span class="line">use admin</span><br><span class="line">show collections</span><br></pre></td></tr></table></figure>

<p>创建用户<br>使用 createUser 创建数据库  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">db.createUser(&#123;</span><br><span class="line">  user:&quot;pan&quot;,   &#x2F;&#x2F; 用户名</span><br><span class="line">  pwd:&quot;123456&quot;, &#x2F;&#x2F; 密码</span><br><span class="line">  customData:&#123;  &#x2F;&#x2F; 个性信息</span><br><span class="line">    name:&quot;潘&quot;,</span><br><span class="line">    age:18</span><br><span class="line">  &#125;,</span><br><span class="line">  roles:[  &#x2F;&#x2F; 配置权限</span><br><span class="line">    &#123;</span><br><span class="line">      role:&#39;readWrite&#39;,  &#x2F;&#x2F; test02 有读写权限</span><br><span class="line">      db:&#39;test02&#39;,</span><br><span class="line">    &#125;,</span><br><span class="line">    &#39;read&#39; &#x2F;&#x2F; 其他所有库只有吟诗权限</span><br><span class="line">  ]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>内置角色<br>数据库用户角色：read、readWrite；<br>数据库管理角色：dbAdmin、dbOwner、userAdmin;<br>集群管理角色：clusterAdmin、clusterManager、clusterMonitor、hostManage；<br>备份恢复角色：backup、restore；<br>所有数据库角色：readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase<br>超级用户角色：root<br>内部角色：__system  </p>
<p>查找用户信息  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.system.users.find()</span><br></pre></td></tr></table></figure>

<p>删除用户  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.system.users.remove(&#123;user:&quot;pan&quot;&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="十六、备份和还原"><a href="#十六、备份和还原" class="headerlink" title="十六、备份和还原"></a>十六、备份和还原</h2><p>备份  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">mongodump</span><br><span class="line">    --host 127.0.0.1</span><br><span class="line">    --port 27017</span><br><span class="line">    --out D:&#x2F;databack&#x2F;backup</span><br><span class="line">    --collection myCollections</span><br><span class="line">    --db test</span><br><span class="line">    --username username</span><br><span class="line">    --password password</span><br><span class="line">mongodump --host 127.0.0.1 --port 27017 --out &#x2F;Users&#x2F;panyongyu&#x2F;Documents&#x2F;study&#x2F;mongodb&#x2F;backup</span><br></pre></td></tr></table></figure>

<p>还原</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">mongorestore</span><br><span class="line">    --host 127.0.0.1</span><br><span class="line">    --port 27017</span><br><span class="line">    --username username</span><br><span class="line">    --password password</span><br><span class="line">    &lt;path to the backup&gt;</span><br><span class="line">mongorestore --host 127.0.0.1 --port 27017 --out &#x2F;Users&#x2F;panyongyu&#x2F;Documents&#x2F;study&#x2F;mongodb&#x2F;backup</span><br></pre></td></tr></table></figure>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">PAN</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://geekweb.site/2019/02/26/MongoDB%E6%95%99%E7%A8%8B/">https://geekweb.site/2019/02/26/MongoDB%E6%95%99%E7%A8%8B/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://geekweb.site" target="_blank">乘风破浪</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/MongoDB/">MongoDB</a></div><div class="post_share"><div class="social-share" data-image="https://i.loli.net/2021/03/26/MqUoIzW5PfNgQKE.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2019/03/29/reacthooks/"><img class="prev-cover" src="https://i.loli.net/2021/03/26/cBT8YwElLCU5qFV.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">React Hooks 入门</div></div></a></div><div class="next-post pull-right"><a href="/2019/02/10/gitignore%E4%B8%8D%E8%B5%B7%E4%BD%9C%E7%94%A8/"><img class="next-cover" src="https://i.loli.net/2021/03/26/dhQMaZic2KpjLsG.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">gitignore不起作用</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="https://i.loli.net/2020/09/25/RVKnjUAof6kryGi.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">PAN</div><div class="author-info__description">研究Web前端开发技术和互联网产品</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">13</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">25</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">7</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">欢迎光临！</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E5%9F%BA%E6%9C%AC%E5%91%BD%E4%BB%A4"><span class="toc-number">1.</span> <span class="toc-text">一、基本命令</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%B0%E5%BB%BA"><span class="toc-number">1.1.</span> <span class="toc-text">新建</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9F%A5%E6%89%BE"><span class="toc-number">1.2.</span> <span class="toc-text">查找</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BF%AE%E6%94%B9"><span class="toc-number">1.3.</span> <span class="toc-text">修改</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%A0%E9%99%A4%E6%95%B0%E6%8D%AE"><span class="toc-number">1.4.</span> <span class="toc-text">删除数据</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%A0%E9%99%A4%E9%9B%86%E5%90%88"><span class="toc-number">1.5.</span> <span class="toc-text">删除集合</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%A0%E9%99%A4%E6%95%B0%E6%8D%AE%E5%BA%93"><span class="toc-number">1.6.</span> <span class="toc-text">删除数据库</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E7%94%A8JS%E5%86%99mongo%E8%AF%AD%E5%8F%A5"><span class="toc-number">2.</span> <span class="toc-text">二、用JS写mongo语句</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%89%E3%80%81%E6%89%B9%E9%87%8F%E6%8F%92%E5%85%A5"><span class="toc-number">3.</span> <span class="toc-text">三、批量插入</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9B%9B%E3%80%81update-%E4%BF%AE%E6%94%B9%E5%99%A8"><span class="toc-number">4.</span> <span class="toc-text">四、update 修改器</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%94%E3%80%81update%E6%95%B0%E7%BB%84%E4%BF%AE%E6%94%B9%E5%99%A8"><span class="toc-number">5.</span> <span class="toc-text">五、update数组修改器</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%AD%E3%80%81%E4%BF%AE%E6%94%B9%E7%9A%84%E7%8A%B6%E6%80%81%E8%BF%94%E5%9B%9E%E4%B8%8E%E5%AE%89%E5%85%A8"><span class="toc-number">6.</span> <span class="toc-text">六、修改的状态返回与安全</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%83%E3%80%81%E6%9F%A5%E8%AF%A2%EF%BC%9Afind%E7%9A%84%E4%B8%8D%E7%AD%89%E4%BF%AE%E9%A5%B0%E7%AC%A6"><span class="toc-number">7.</span> <span class="toc-text">七、查询：find的不等修饰符</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%AB%E3%80%81%E6%9F%A5%E8%AF%A2%EF%BC%9Afind%E7%9A%84%E5%A4%9A%E6%9D%A1%E4%BB%B6%E6%9F%A5%E8%AF%A2"><span class="toc-number">8.</span> <span class="toc-text">八、查询：find的多条件查询</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B9%9D%E3%80%81%E6%9F%A5%E8%AF%A2%EF%BC%9Afind%E6%95%B0%E7%BB%84%E6%9F%A5%E8%AF%A2"><span class="toc-number">9.</span> <span class="toc-text">九、查询：find数组查询</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%81%E3%80%81%E6%9F%A5%E8%AF%A2%EF%BC%9Afind%E5%8F%82%E6%95%B0"><span class="toc-number">10.</span> <span class="toc-text">十、查询：find参数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%81%E4%B8%80%E3%80%81%E7%B4%A2%E5%BC%95%E5%85%A5%E9%97%A8"><span class="toc-number">11.</span> <span class="toc-text">十一、索引入门</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%81%E4%BA%8C%E3%80%81%E5%A4%8D%E5%90%88%E7%B4%A2%E5%BC%95"><span class="toc-number">12.</span> <span class="toc-text">十二、复合索引</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%81%E5%9B%9B%E3%80%81%E5%85%A8%E6%96%87%E7%B4%A2%E5%BC%95"><span class="toc-number">13.</span> <span class="toc-text">十四、全文索引</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%81%E4%BA%94%E3%80%81%E7%AE%A1%E7%90%86-%E7%94%A8%E6%88%B7%E7%9A%84%E5%88%9B%E5%BB%BA%E3%80%81%E5%88%A0%E9%99%A4%E4%B8%8E%E4%BF%AE%E6%94%B9"><span class="toc-number">14.</span> <span class="toc-text">十五、管理:用户的创建、删除与修改</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%81%E5%85%AD%E3%80%81%E5%A4%87%E4%BB%BD%E5%92%8C%E8%BF%98%E5%8E%9F"><span class="toc-number">15.</span> <span class="toc-text">十六、备份和还原</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2022/11/25/http%E5%9B%BE%E8%A7%A3/" title="http图解"><img src="https://i.loli.net/2021/03/26/YT1hgRiNql7V3Hz.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="http图解"/></a><div class="content"><a class="title" href="/2022/11/25/http%E5%9B%BE%E8%A7%A3/" title="http图解">http图解</a><time datetime="2022-11-25T02:46:58.000Z" title="发表于 2022-11-25 10:46:58">2022-11-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2019/04/20/%E5%A6%82%E4%BD%95%E4%BF%9D%E8%AF%81%E9%A1%B5%E9%9D%A2%E6%96%87%E4%BB%B6%E8%83%BD%E8%A2%AB%E5%AE%8C%E6%95%B4%E9%80%81%E8%BE%BE%E6%B5%8F%E8%A7%88%E5%99%A8/" title="如何保证页面文件能被完整送达浏览器？"><img src="https://i.loli.net/2021/03/26/dhQMaZic2KpjLsG.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="如何保证页面文件能被完整送达浏览器？"/></a><div class="content"><a class="title" href="/2019/04/20/%E5%A6%82%E4%BD%95%E4%BF%9D%E8%AF%81%E9%A1%B5%E9%9D%A2%E6%96%87%E4%BB%B6%E8%83%BD%E8%A2%AB%E5%AE%8C%E6%95%B4%E9%80%81%E8%BE%BE%E6%B5%8F%E8%A7%88%E5%99%A8/" title="如何保证页面文件能被完整送达浏览器？">如何保证页面文件能被完整送达浏览器？</a><time datetime="2019-04-20T04:23:08.000Z" title="发表于 2019-04-20 12:23:08">2019-04-20</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2019/04/15/jscopy/" title="如何实现一个深浅拷贝"><img src="https://i.loli.net/2021/03/26/JmzkRwbiO7G1Tqx.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="如何实现一个深浅拷贝"/></a><div class="content"><a class="title" href="/2019/04/15/jscopy/" title="如何实现一个深浅拷贝">如何实现一个深浅拷贝</a><time datetime="2019-04-15T13:11:06.000Z" title="发表于 2019-04-15 21:11:06">2019-04-15</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2019/04/07/jsprototype/" title="JS原型和原型链"><img src="https://i.loli.net/2021/03/26/cBT8YwElLCU5qFV.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JS原型和原型链"/></a><div class="content"><a class="title" href="/2019/04/07/jsprototype/" title="JS原型和原型链">JS原型和原型链</a><time datetime="2019-04-07T04:30:08.000Z" title="发表于 2019-04-07 12:30:08">2019-04-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2019/04/02/jsdata/" title="JS的数据类型"><img src="https://i.loli.net/2021/03/26/cBT8YwElLCU5qFV.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JS的数据类型"/></a><div class="content"><a class="title" href="/2019/04/02/jsdata/" title="JS的数据类型">JS的数据类型</a><time datetime="2019-04-02T03:22:00.000Z" title="发表于 2019-04-02 11:22:00">2019-04-02</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2018 - 2023 By PAN</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"></div><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-show-text.min.js" data-mobile="false" data-text="I,LOVE,YOU,富强,民主,文明,和谐,平等,公正,法治,爱国,敬业,诚信,友善" data-fontsize="15px" data-random="false" async="async"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>